import { RequestDTO } from "@/dto/general";

var eleNodeList;
const getElementByTagName = (tagName: string) => {
  var eleList: HTMLCollectionOf<Element> =
    document.getElementsByTagName(tagName);
  return eleList;
};

// 打开接收消息的端口
const startListeningPortContent = () => {
  browser.runtime.onMessage.addListener((message: RequestDTO) => {
    if (message.to === "content") {
      dealPopupGeteleList(message);
    }
  });
};

const dealPopupGeteleList = (message: RequestDTO) => {
  if (message.action === "getEleList") {
    sendToPopupSelectorInfo();
  }
};

const sendMessage = (name: string, action: string, data: object) => {
  var port = browser.runtime.connect({ name: "content" });
  var message: RequestDTO = new RequestDTO("content", name, data, action);
  port.postMessage(message);
  port.disconnect();
};

const sendToPopupSelectorInfo = () => {
  // var eleList = getElementByTagName("select")
  var eleList = document.getElementsByClassName("ivu-select-dropdown-list");
  var i = 0
  for(var ele of eleList){
    i+= 1
    var childList = ele.getElementsByClassName("ivu-select-item")
    if(childList.length == 0){
      continue
    }

    if(i > 1 && i < 10){
      var eleNode = childList[0] as HTMLElement | null
      eleNode?.click()
    }

  }
  var data = { num: eleList.length };

  sendMessage("popup", "sendSelectorInfo", data);
};

// const dealClick = (e:any) => {
//   sendMessage("popup")
//   console.log(e.target.tagName)
// }

export default defineContentScript({
  matches: ["*://*/*"],
  main() {
    console.log("content loading done.");
    startListeningPortContent();
    sendToPopupSelectorInfo();
  },
});
